import $http from '../../http/http.js'
import apiSetting from '../../http/apiSetting.js'
let dayjs = require('dayjs');
let app = getApp();

Page({
  data: {
    intervalNum: 60,
    interval: null,
    isInterval: false,
    // 手机号
    phoneNumber: '',
    // 验证码
    randomCode: '',
    isClick: false
  },
  onLoad() {

  },

  onUnload() {
    // 页面被关闭
    clearInterval(this.data.interval)
  },


  phoneNumberInp(e) {
    this.data.phoneNumber = e.detail.value
  },

  randomCodeInp(e) {
    this.data.randomCode = e.detail.value
  },

  countDown() {
    let that = this
    if (that.data.phoneNumber == '') {
      dd.showToast({
        type: 'fail ',
        content: '请填写手机号',
        duration: 1000,
      });
      return false
    }
    that.getSendSms()
    that.setData({
      isInterval: true
    })
    that.data.interval = setInterval(function () {
      that.setData({
        intervalNum: that.data.intervalNum - 1
      })
      if (that.data.intervalNum <= 0) {
        clearInterval(that.data.interval)
        that.setData({
          isInterval: false,
          intervalNum: 60
        })
      }
    }, 1000)
  },

  // 获取短信验证码
  getSendSms() {
    let that = this
    $http(apiSetting.sendSms, {
      phoneNumber: that.data.phoneNumber
    }).then((data) => {
      console.log(data)
      if (data.code == 0) {

      }
    })
  },

  // 登录
  verifyCode() {
    let that = this
    if (!that.formVerify()) {
      return
    }
    that.setData({
      isClick: true
    })
    $http(apiSetting.verifyCode, {
      phoneNumber: that.data.phoneNumber,
      randomCode: that.data.randomCode
    }).then((data) => {
      if (data.code == 0) {
        dd.reLaunch({
          url: '/pages/index/index'
        })
      } else {
        that.setData({
          isClick: false
        })
      }
    })
  },

  formVerify() {
    let that = this
    if (that.data.isClick) {
      return false
    }
    if (that.data.phoneNumber == '') {
      dd.showToast({
        type: 'fail ',
        content: '请填写手机号',
        duration: 1000,
      });
      return false
    }
    if (that.data.randomCode == '') {
      dd.showToast({
        type: 'fail ',
        content: '请填写验证码',
        duration: 1000,
      });
      return false
    }
    return true
  }
});
